
<template>
  <div>
    <!-- <el-form-item label="上传落地页图片" label-width="140px" class="upload-form-item"
                                    style="margin-top: 23px;"> -->
    <!-- <span slot="label"><span style="color:#f56c6c">*</span>上传落地页图片</span> -->
    <input
      type="file"
      style="display: none"
      ref="filesRef"
      @change="loadImage"
    />
    <div>
      <div
        class="upload-img"
        v-for="(item, index) in uploadbackUrlDataPreview"
        :key="index"
        style="margin-left: 5px"
      >
        <!-- <div @click="del3(index)" style="position: absolute; left: 10px;">X</div>  -->
        <div
          v-if="item.index == 2"
          style="
            position: absolute;
            background-color: rgba(250, 250, 250, 0.6);
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
          "
        >
          <div
            class="upload-title"
            style="color: #43a3ef"
            @click="uploadbackUrlDel(index)"
          >
            重新上传
          </div>
        </div>
        <div
          v-if="item.index != 2 && item.index != 3"
          style="
            position: absolute;
            background-color: rgba(250, 250, 250, 0.6);
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
          "
        >
          <div class="upload-title" style="color: #abb2bf">上传中</div>
        </div>
        <div
          v-if="item.index == 3"
          @click.stop="replaceUpload(index)"
          style="position: absolute; top: 0; bottom: 0; right: 0; left: 0"
          class="del_upload_s"
        >
          <center>
            <span class="del_upload" @click.stop="handleImgClick(item, index)">
              <div style="display: flex; font-size: 12px">
                <!-- <i
                  class="el-icon-refresh refreshClass"
                  style="font-size: 18px"
                  @click="replaceUpload(index)"
                ></i> -->
                <!-- <i
                  class="el-icon-close refreshClass"
                  style="font-size: 18px"
                  @click="uploadbackUrlDel(index)"
                ></i> -->
                <span>预览</span>
                <!-- <i
                  class="el-icon-zoom-in refreshClass"
                  @click="handleImgClick(item, index)"
                  style="font-size: 18px"
                ></i> -->
              </div>
            </span>
          </center>
        </div>
        <img :src="item.val" alt="" style="width: 100%; height: 100%" />
      </div>
      <div
        class="upload-img"
        style="color: #f5f5f5"
        @click="uploadbackUrl"
        v-if="uploadbackUrlDataPreview.length != uploadNumber"
      >
        <i class="el-icon-plus plusIcon"></i>
          <div class="lengthClass"
            >{{ title }}({{ uploadbackUrlDataPreview.length }}/{{
              uploadNumber
            }})
            <div class="textView">{{ text }}</div>
            </div
          >
      </div>
    </div>
    <!-- 图片预览  开始  -->
    <el-image
      ref="elImageRef"
      v-show="false"
      class="img"
      :src="imgUrl"
      :preview-src-list="imgList"
    >
    </el-image>
    <!-- 图片预览  结束 -->
    <!-- </el-form-item> -->
  </div>
</template>

<script>
  import { uploadURL } from "@/api/config.json";
  import axios from "axios"
export default {
  props: {
    // 上传描述
    text: {
      type: String,
      default: "",
    },
    // 上传描述
    urls: {
      type: String,
      default: "",
    },
    // 上传描述
    flag: {
      type: String,
      default: "",
    },
    // 上传数量
    uploadNumber: {
      type: Number,
      default: 100,
    },
    // 上传返回
    flags: {
      type: String,
      default: '',
    },
    // 文件最大
    max: {
      type: Number,
      default: 100,
    },
    // 上传名称
    title: {
      type: String,
      default: "",
    },
    // 上传格式
    format: {
      type: Array,
    },
    // 接口传输files名称
    filesName: {
      type: String,
      default: "file",
    },
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      imgList: [],
      imgUrl: "",
      disabled: false,
      uploadIdentifier: "", // 更换标识符
      uploadbackUrlData: [], // 上传图片
      uploadbackUrlDataPreview: [], // 上传图片预览
    };
  },
  methods: {
    reset() {
      this.uploadbackUrlData = []
      this.uploadbackUrlDataPreview = []
    },
    // 修改数据
    echo(val, name) {
      this.uploadbackUrlData = []
      this.uploadbackUrlDataPreview = []
        val.forEach(element => {
            console.log(element[name])
            this.uploadbackUrlData.push({
                value: 3,
                files: element[name],
                upload: false,
                media_id: element.media_id || 0
            })
            this.uploadbackUrlDataPreview.push({
                index: 3,
                val: element[name],
                upload: false,
                media_id: element.media_id || 0
            })
        });
    },
    // 更换上传
    replaceUpload(index) {
      if (this.flags == 2) return
      this.uploadIdentifier = index;
      // this.uploadbackUrlDataPreview.splice(index, 1)
      // this.uploadbackUrlData.splice(index, 1)
      this.$refs.filesRef.value = "";
      this.$refs.filesRef.click();
    },
    // 查看大图
    handleImgClick(i, index) {
      console.log(i, index, this.uploadbackUrlData[index], this.uploadbackUrlData[index])
      this.imgList = [this.uploadbackUrlData[index].files]; // 需要的预览列表图片地址
      this.$refs.elImageRef.showViewer = true; // 这个属性就可以控制 预览视图打开
    },
    /** 上传 */
    async loadImage() {
      if (this.flags == 2) return
      const fileSplit = this.$refs.filesRef.files[0].name.split(".")
      console.log(this.$refs.filesRef.files[0].size, this.max * 1024 * 1024);
      if (this.$refs.filesRef.files[0].size > this.max * 1024 * 1024) {
        console.log(this.max)
        this.$message.error(`请上传小于${this.max}MB`);
        return false;
      }
      console.log(this.format, fileSplit[fileSplit.length - 1], this.max)
      if (
        !this.format.includes(
          fileSplit[fileSplit.length - 1]
        )
      ) {
        this.$message.error(`请上传正确格式${this.format.join()}`);
        return false;
      }
      if (this.uploadbackUrlData == this.uploadNumber) {
        this.$message.error(`仅支持上传${uploadNumber}个`);
        return false;
      }
      try {
        if (this.uploadIdentifier === "") {
          for (
            let index = 0;
            index < this.$refs.filesRef.files.length;
            index++
          ) {
            try {
              const reader = new FileReader();
              reader.onload = (e) => {
                this.uploadbackUrlDataPreview.push({
                  val: e.target.result,
                  index: 0,
                });
              };
              reader.readAsDataURL(this.$refs.filesRef.files[index]);
            } catch (err) {
              this.$message.error(err);
            }
            let upload = await this.upload(
              this.$refs.filesRef.files[index],
              index
            );
            setTimeout(() => {
              if (+upload.value > -1 && !upload.upload) {
                let numberPng =
                  this.uploadbackUrlDataPreview.length + upload.value - 1;
                if (this.uploadbackUrlDataPreview[numberPng]) {
                  this.uploadbackUrlDataPreview[numberPng].index = 2;
                }
              } else {
                let numberPng =
                  this.uploadbackUrlDataPreview.length + upload.value - 1;
                this.uploadbackUrlDataPreview[numberPng].index = 3;
                console.log(upload);
                this.uploadbackUrlData.push(upload);
              }
            });
          }
        } else {
          try {
            const reader = new FileReader();
            reader.onload = (e) => {
              this.uploadbackUrlDataPreview.splice(this.uploadIdentifier, 1, {
                val: e.target.result,
                index: 0,
              });
              this.uploadbackUrlData.splice(this.uploadIdentifier, 1);
            };
            reader.readAsDataURL(this.$refs.filesRef.files[0]);
          } catch (err) {
            this.$message.error(err);
          }
          let upload = await this.upload(
            this.$refs.filesRef.files[0],
            this.uploadIdentifier
          );
          setTimeout(() => {
            if (+upload.value > -1 && !upload.upload) {
              let numberPng =
                this.uploadbackUrlDataPreview.length + upload.value - 1;
              if (this.uploadbackUrlDataPreview[this.uploadIdentifier]) {
                this.uploadbackUrlDataPreview[this.uploadIdentifier].index = 2;
              }
            } else {
              this.uploadbackUrlDataPreview[this.uploadIdentifier].index = 3;
              this.uploadbackUrlData.push(upload);
              this.uploadIdentifier = "";
            }
          });
        }
      } catch (err) {
        this.$message.error(err);
      }
    },
    /** 上传 */
    uploadbackUrl() {
      if (this.flags == 2) return
      if (this.uploadbackUrlDataPreview.length == this.uploadNumber) {
        this.$message.error(`多只能上传${this.uploadNumber}张${this.prompt}`);
        return false;
      } else {
        this.$refs.filesRef.value = "";
        this.$refs.filesRef.click();
      }
    },
    async upload(val, index) {
      let files = val;
      try {
        let formData = new FormData()
        const binaryData = new Blob([files], { type: 'application/octet-stream' })
        const newFile = new File([binaryData], 'newFileName', { type: binaryData.type || 'application/octet-stream' });
        console.log(newFile, '获取数据')
        formData.append(this.filesName, new File([binaryData], 'newFileName', { type: binaryData.type || 'application/octet-stream' }));
        let token = localStorage.getItem('token')
        formData.append('user_token' , token);
        let res = ''
        if (this.flag == '') {
          res = await axios.post(uploadURL, {formData, responseType: 'blob' }, true)
          console.log(res, '执行1')
        } else {
          res = await axios.post(uploadURL, {formData, responseType: 'blob' }, true)
          console.log(res, '执行2')
          // 新的接口
        }
        console.log(res)
        let acc = ''
        if (this.urls == '11') {
          if (this.flag == '') {
            console.log(res, '执行3')
            acc = await axios.post(uploadURL, {formData, responseType: 'blob' }, true)
        } else {
          // 新的接口
          console.log(res, '执行4')
          acc = await axios.post(uploadURL, {formData, responseType: 'blob' }, true)
        }
        }
        console.log(acc)
        this.$message.success("上传成功");
        return {
          files: res.url,
          value: index,
          upload: true,
          media_id: this.urls == '11' ? acc.media_id : ''
        };
      } catch (err) {
        console.log(err, '获取失败原因', uploadURL)
        this.$message.error(err.response.data.message);
        return { files: files, value: index, upload: false };
      }
    },
    /** 删除 */
    uploadbackUrlDel(index) {
      this.uploadbackUrlDataPreview.splice(index, 1);
      this.uploadbackUrlData.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.upload-title {
  position: absolute;
  top: 50%;
  left: 50%;
  color: gray;
  transform: translate(-50%, -50%);
}
// .del_upload_s:hover {
//   .del_upload {
//     display: flex;
//     color: #fff;
//     font-size: 12px;
//     text-align: center;
//     padding-left: 67px;
//   }
// }
.refreshClass:hover {
  color: #409eff;
}
.lengthClass {
  color: rgba(109, 114, 120, 0.50); 
  font-size: 12px;
  line-height: 1;
  padding-top: 7px;
  text-align: center;
  .textView {
    margin-top: 10px;
  }
}
.del_upload {
  background: rgba(0,0,0,0.25);
  border-radius: 0px 0px 4px 4px;
  color: #fff;
  position: absolute;
  justify-content: center;
  text-align: center;
  left: 0;
  right: 0;
  font-size: 12px;
  height: 20px;
  bottom: 0;
  line-height: 13px;
  text-align: center;
  display: flex;
  align-items: center;
}
.upload-img {
  width: 180px;
  height: 134px;
  border: 1px dashed #ddd;
  cursor: pointer;
  border-radius: 4px;
  position: relative;
  background-color: rgba(245, 245, 245, 1);
  color: #0000001c !important;

  .plusIcon {
    font-size: 30px;
    color: #c0c4cc;
    display: block;
    text-align: center;
    margin-top: 16%;
  }

  &:hover {
    border: 1px dashed #409eff;
    .plusIcon {
      color: #409eff;
    }
  }
}
</style>
